﻿using System;
using System.Device.Location;
using GalaSoft.MvvmLight.Threading;
using Microsoft.WindowsAzure.MobileServices;
using SkiTracker.Model;
using Windows.Devices.Geolocation;

namespace SkiTracker.ViewModel
{
    public class ShowFriendsViewModel : MapViewModel
    {

        private readonly IMobileServiceTable<Device> _deviceTable = App.MobileService.GetTable<Device>();
        private Geolocator _geolocator;

        public ShowFriendsViewModel()
        {
            GetFriends();
            GetCurrentPosition();
        }

        private void GetFriends()
        {
            Friends = _deviceTable
                .Where(d => d.GroupName == App.CurrentApp.CurrentDevice.GroupName
                            && d.Id != App.CurrentApp.CurrentDevice.Id)
                .ToCollectionView();
        }

        private async void GetCurrentPosition()
        {
            _geolocator = new Geolocator
            {
                DesiredAccuracy = PositionAccuracy.High,
            };

            var geoposition = await _geolocator.GetGeopositionAsync(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15));
            CurrentLocation = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude);

        }

        private GeoCoordinate _currentLocation;
        public virtual GeoCoordinate CurrentLocation
        {
            get { return _currentLocation; }
            set
            {
                _currentLocation = value;

                DispatcherHelper.CheckBeginInvokeOnUI(() => RaisePropertyChanged(() => CurrentLocation));

            }
        }

        private MobileServiceCollectionView<Device> _friends;
        public MobileServiceCollectionView<Device> Friends
        {
            get { return _friends; }
            private set
            {
                _friends = value;
                RaisePropertyChanged(() => Friends);
            }
        }
    }
}